/**
 * 
 */
package edu.mse.camel.client.session.views;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;

import edu.mse.camel.client.eventbus.pubsub.EventManager;
import edu.mse.camel.client.eventbus.pubsub.ISubscriber;
import edu.mse.camel.client.events.EventIDs;
import edu.mse.camel.client.events.IEvent;
import edu.mse.camel.client.session.handlers.ReceiveInvitationEventHandler;
import edu.mse.camel.client.session.team.TeamList;

class ViewContentProvider implements IStructuredContentProvider, ISubscriber {

	/**
	 * 
	 */
	private final TeamView teamViewContentProvider;
	private ReceiveInvitationEventHandler rieHandler;



	public ViewContentProvider(TeamView teamView) {
		teamViewContentProvider = teamView;
		//TODO
		EventManager.getInstance().subscribeTo(EventIDs.CLIENT_INTERNAL_EVENT, this);
		rieHandler = new ReceiveInvitationEventHandler();
		EventManager.getInstance().subscribeTo(EventIDs.RECEIVE_INVITE_EVENT,
				rieHandler);
	}

	public void inputChanged(Viewer v, Object oldInput, Object newInput) {
	}

	public void dispose() {
		EventManager.getInstance().unSubscribeTo(EventIDs.CLIENT_INTERNAL_EVENT, this);
		EventManager.getInstance().unSubscribeTo(EventIDs.RECEIVE_INVITE_EVENT, rieHandler);
	}

	public Object[] getElements(Object parent) {
		return TeamList.getInstance().getMembers().toArray();
	}

	@Override
	public void notifyEvent(IEvent e) {
		if (teamViewContentProvider != null) {
			if (teamViewContentProvider.viewer != null) {
				Control ctrl = teamViewContentProvider.viewer.getControl();
				if (ctrl != null && !ctrl.isDisposed()) {
					Display display = ctrl.getDisplay();
					if (display != null) {
						display.asyncExec(new Runnable() {
		
							@Override
							public void run() {
								teamViewContentProvider.viewer.refresh();
							}
		
						});
					}
				}
			}
		}
	}
}